﻿using DotNetty.Transport.Channels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ShaoLuNettyServer
{
    public class TcpServerHandler : SimpleChannelInboundHandler<string>
    {

        private static readonly log4net.ILog Logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        protected override void ChannelRead0(IChannelHandlerContext context, string message)
        {
            Console.WriteLine($"Received data: {message}");

            Logger.Info($"Received data: {message}");

            // 在这里处理接收到的数据
            Logger.Info("我是服务器");
            context.Channel.WriteAndFlushAsync("我是服务器");
        }

        public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
        {
            Logger.Info($"Exception: {exception}");
            Console.WriteLine($"Exception: {exception}");
            context.CloseAsync();
        }

        public override void ChannelActive(IChannelHandlerContext context)
        {
            string clientName = context.Channel.RemoteAddress.ToString();

            // 打印客户端名称
            Console.WriteLine("连接到一台客户端：" + clientName);
            Logger.Info("连接到一台客户端：" + clientName);
            base.ChannelActive(context);
            Console.WriteLine("连接到一台客户端：" + clientName);
        }

    }
}
